package com.snow.datasource.strategy;

import cn.hutool.core.collection.CollectionUtil;
import com.snow.datasource.properties.DataSourceProperty;
import com.snow.datasource.properties.SnowFlakeProperties;
import com.snow.datasource.route.SnowRoutingDataSource;
import com.snow.datasource.strategy.annoation.Strategy;
import com.snow.datasource.strategy.enums.HandleStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 均衡策略
 *
 * @Description
 * @Author fanxl
 * @Date 2020/12/23
 **/
@Strategy(value = HandleStrategy.LOAD_BALANCE)
public class LoadBalanceStrategy implements IStrategy , BeanPostProcessor {

    @Autowired
    private SnowRoutingDataSource snowRoutingDataSource;

    private AtomicInteger index = new AtomicInteger(0);

    @Override
    public String getDataBaseKey() {
        return null;
    }

    @Override
    public String getSlaveKey() {
        if(CollectionUtil.isEmpty(snowRoutingDataSource.getDataSourceSlaves())){
            return snowRoutingDataSource.getPrimary();
        }
        return snowRoutingDataSource.getDataSourceSlaves().get(index.getAndAdd(1) % snowRoutingDataSource.getDataSourceSlaves().size());
    }
}
